<template>
    <div class="mybody_">
        <div class="mycentered">
            <div class="myheader_">
                <div class="_back"><a href="#/setup" style="text-decoration: none;">&lt;</a></div>
                <div class="mine_">
                    <span>个人资料</span>
                </div>
            </div>
            <el-form ref="form" :model="studentData" label-width="150px">
                <el-form-item label="头像" type="file" v-model="studentData.image">
                    <el-upload :show-file-list="false" :before-upload="uploadImage">
                        <el-button size="small" type="primary" :disabled="!isEditing">点击更换</el-button>
                    </el-upload>
                    <el-image v-if="studentData.image" :src="studentData.image"
                        style="max-height: 150px; max-width: 150px;"></el-image>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="studentData.name" :disabled="!isEditing" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="studentData.gender" placeholder="请选择" :disabled="!isEditing">
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="studentData.phone" :disabled="true" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="微信号">
                    <el-input v-model="studentData.weChat" :disabled="!isEditing" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="年龄">
                    <el-input v-model="studentData.age" :disabled="!isEditing" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="studentData.email" :disabled="!isEditing" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="学历">
                    <el-select v-model="studentData.education" :disabled="!isEditing" style="width: 300px;">
                        <el-option label="小学" value="小学"></el-option>
                        <el-option label="初中" value="初中"></el-option>
                        <el-option label="高中" value="高中"></el-option>
                        <el-option label="本科" value="本科"></el-option>
                        <el-option label="研究生" value="研究生"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生日">
                    <el-date-picker v-model="studentData.birthday" type="date" placeholder="选择日期" :editable="false"
                        :clearable="!isEditing" :disabled="!isEditing" style="width: 300px;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="籍贯">
                    <el-input v-model="studentData.ancestral" :disabled="!isEditing" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="民族">
                    <el-select v-model="studentData.nation" placeholder="请选择" :disabled="!isEditing">
                        <el-option v-for="item in nations" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="技能">
                    <el-input v-model="studentData.skill" :disabled="!isEditing" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="studentData.address" :disabled="!isEditing" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item>
                    <div v-if="isEditing">
                        <el-button type="primary" @click="saveForm">保存</el-button>
                        <el-button @click="cancelEdit">取消</el-button>
                    </div>
                    <div v-else>
                        <el-button @click="startEdit">编辑</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
  
<script>
import { jwtDecode } from 'jwt-decode';
import regionData from '@/data/regionData.json'; // 导入本地JSON文件

export default {
    name: "Login",
    name: 'LoginView',
    data() {
        return {
            nations: ['汉族', '壮族', '满族', '藏族', '维吾尔族', '苗族', '彝族', '布依族', '侗族', '瑶族', '白族', '土家族', '哈尼族', '哈萨克族', '傣族', '黎族', '傈僳族', '佤族', '畲族', '高山族', '拉祜族', '水族', '东乡族', '纳西族', '景颇族', '柯尔克孜族', '土族', '达斡尔族', '仫佬族', '羌族', '布朗族', '撒拉族', '毛南族', '仡佬族', '锡伯族', '阿昌族', '普米族', '塔吉克族', '怒族', '乌孜别克族', '俄罗斯族', '鄂温克族', '德昂族', '保安族', '裕固族', '京族', '塔塔尔族', '独龙族', '鄂伦春族', '赫哲族', '门巴族', '珞巴族', '基诺族'],
            form: {},
            rules: {
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        type: 'string', message: '请输入不包含空格的字符', trigger: 'blur', transform(value) {
                            if (value && value.indexOf(' ') === -1) {
                                return value
                            } else {
                                return false
                            }
                        }
                    },
                    {
                        trigger: 'blur', validator: (rule, value, callback) => {
                            var passwordreg = /(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,10}/
                            if (!passwordreg.test(value)) {
                                callback(new Error('密码必须由数字、字母、特殊字符组合,请输入6-10位'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
            },
            Admin: {
                phone: '',
                password: ''
            },
            studentData: {
            },
            isEditing: false,
        };
    },
    methods: {

        // 上传以及校验
        uploadImage(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image.png';
            if (!isJPG && !isPNG) {
                this.$message.error('只能上传JPG/PNG格式的图片');
                return false;
            }
            const formData = new FormData();
            formData.append('file', file);
            this.$http.post('/api/upload', formData, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
            })
                .then(response => {
                    if (response && response.data && response.data.data) {
                        this.imageUrl = response.data.data;
                        this.studentData.image = this.imageUrl;
                    }
                })
                .catch(error => {
                    console.error(error);
                });
            return false; // 阻止自动上传
        },

        //编辑状态的更换
        startEdit() {
            this.isEditing = true;
        },
        saveForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    // 保存表单数据的逻辑
                    this.isEditing = false;
                    this.$http.put('/api/students/updateStudents', this.studentData).then(() => {
                        this.$message.success('修改成功');
                        const jwt = localStorage.getItem('jwt');
                        if (jwt) {
                            const decoded = jwtDecode(jwt);
                            const userId = decoded.id; // 确保你的token结构中有id字段
                            this.$http.get("/api/students/queryOneStudentById/" + userId).then(response => {  /*刷新页面*/
                                this.studentData = response.data.data;
                            }).catch(() => {
                                this.$message.error("请求错误");
                            });
                        }
                    })
                }
            });
        },
        cancelEdit() {
            this.isEditing = false;
        },

        gotoRegister() {
            // 跳转注册页面
            this.$router.push('/register');
        },
        login() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (!this.form.validCode) {
                        this.$message.error("请填写验证码")
                        return
                    }
                    if (this.form.validCode.toLowerCase() !== this.validCode.toLowerCase()) {
                        this.$message.error("验证码错误")
                        return
                    }
                    this.$http.post("/api/studentLogin", {
                        phone: this.form.phone,
                        password: this.form.password
                    }, {
                        headers: {
                            'Content-Type': 'application/json'
                        },
                    }).then(response => {
                        if (response.data.code == 1) {
                            this.$message.success("登录成功");
                            // 登录成功，将令牌存储在localStorage中
                            localStorage.setItem('jwt', response.data.data);
                            //把username传到下一个页面
                            localStorage.setItem('phone', this.form.phone);
                            this.$router.push({ path: '/index', query: { phone: this.form.phone } });

                        }
                        else this.$message.error(response.data.message);
                    })
                        .catch(error => {
                            console.log(error)
                        })
                }
            });
        },
    },
    mounted() {
        const jwt = localStorage.getItem('jwt');
        if (jwt) {
            const decoded = jwtDecode(jwt);
            const userId = decoded.id; // 确保你的token结构中有id字段
            this.$http.get("/api/students/queryOneStudentById/" + userId).then(response => {  /*刷新页面*/
                this.studentData = response.data.data;
            }).catch(() => {
                this.$message.error("请求错误");
            });
            // this.$http.get("/api/orders/queryOneStudentOrder/" + userId).then(response => {  /*刷新页面*/
            //     this.orderData = response.data.data.rows;
            // }).catch(() => {
            //     this.$message.error("请求错误");
            // });
            // 将导入的本地JSON文件赋值给regionOptions

        }
    },
};
</script>
  
<style>
@import "@/style/my.css";
</style>